package com.tbit.uqbike.client.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipayEncrypt;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.AliConfig;
import com.tbit.uqbike.client.pojo.AliConfigWrap;
import com.tbit.uqbike.client.pojo.ZfbPayConfig;
import com.tbit.uqbike.client.service.AliConfigService;
import com.tbit.uqbike.client.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: chen
 * @Description:
 * @Date: 创建于 10:08 2020/10/19
 */
@Service
@Slf4j
public class AliConfigServiceImpl implements AliConfigService {


    @Autowired
    private RedisService redisService;

    @Override
    public AliConfigWrap getAliPayClient(Integer accountId, ZfbPayConfig zfbPayConfig) {
        AliConfig aliConfig = new AliConfig();
        aliConfig.setPartner(zfbPayConfig.getPartner());   //商户号
        aliConfig.setAli_public_key(zfbPayConfig.getAli_public_key()); //支付宝公钥
        aliConfig.setPrivate_key(zfbPayConfig.getPrivate_key());   //应用私钥
        aliConfig.setDecryptKey(zfbPayConfig.getDecryptKey()); //密钥
        /**支付宝支付连接客户端*/
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                aliConfig.getPartner(), aliConfig.getPrivate_key(), "JSON", "UTF-8",
                aliConfig.getAli_public_key(), "RSA2");
        AliConfigWrap aliConfigWrap = new AliConfigWrap();
        BeanUtils.copyProperties(aliConfig, aliConfigWrap);
        aliConfigWrap.alipayClient = alipayClient;

        return aliConfigWrap;
    }

    @Override
    public AlipaySystemOauthTokenResponse alipaySystemOauthToken(Integer accountId, String authCode, ZfbPayConfig zfbPayConfig) {
        AliConfigWrap aliConfigWrap = getAliPayClient(accountId, zfbPayConfig);
        return alipaySystemOauthToken(aliConfigWrap.getAlipayClient(), authCode);
    }


    /**
     * 获取支付宝小程序用户id及token
     *
     * @param alipayClient 支付宝客户端
     * @param authCode     小程序授权code
     * @return
     */
    private AlipaySystemOauthTokenResponse alipaySystemOauthToken(AlipayClient alipayClient, String authCode) {
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("authorization_code");
        request.setCode(authCode);
        try {
            AlipaySystemOauthTokenResponse response = alipayClient.execute(request);

            log.info("userid: " + response.getUserId() + "  accesstoken令牌: " + response.getAccessToken() +
                    "  访问令牌有效时间: " + response.getExpiresIn() + "  刷新令牌有效时间: " + response.getReExpiresIn() + "  刷新令牌: " + response.getRefreshToken());
            if (response.isSuccess()) {
                return response;
            } else {
                log.error("错误" + response.getCode() + response.getMsg());
                throw new BaseException("-101", response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            log.error("Failed to request alipay.system.oauth.token.", e);
            throw new BaseException("-101", "系统异常");
        }
    }

    @Override
    public String decryptPhone(Integer accountId, String sign, String content, ZfbPayConfig zfbPayConfig) {
        AliConfigWrap aliConfigWrap = getAliPayClient(accountId, zfbPayConfig);
        return decryptPhone(aliConfigWrap.getAli_public_key(), aliConfigWrap.getDecryptKey(), sign, content);
    }

    /**
     * 手机号码解密
     *
     * @param signVerifyKey 支付宝公钥
     * @param decryptKey    解密秘钥
     * @param sign          签名
     * @param content       解密字段
     * @return
     */
    private String decryptPhone(String signVerifyKey, String decryptKey, String sign, String content) {
        String signType = "RSA2";
        String charset = "UTF-8";
        String encryptType = "AES";
        String signContent = content;
        signContent = "\"" + signContent + "\"";
        try {
            if (!AlipaySignature.rsaCheck(signContent, sign, signVerifyKey, charset, signType)) {
                log.error("验签失败");
                return null;
            }
        } catch (AlipayApiException e) {
            log.error("alipay sign check fail. ", e);
            return null;
        }

        try {
            String plainData = AlipayEncrypt
                    .decryptContent(content, encryptType, decryptKey, charset);
            log.info("AlipayEncrypt.decryptContent: " + plainData);
            return JSONObject.parseObject(plainData).get("mobile").toString();
        } catch (AlipayApiException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }


    public static void main(String[] args) {
        AliConfigService aliConfigService = new AliConfigServiceImpl();

        ZfbPayConfig zfbPayConfig = new ZfbPayConfig();
        zfbPayConfig.setPartner("2021004139602077");
        zfbPayConfig.setPrivate_key("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCnBHcUYyBrP3PCdaC7auWFmWGc0RDstnvyd8osjcFkIoxPdHQtj6oRBzLTmGJFJLB1tPGkOwOd7ySOJNGeNEOHPYPiuQ6SW5bVuYqatpWj37giwN92w2n4IN3aUVe3Q8T6Rttu");
        zfbPayConfig.setAli_public_key("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjp2zDSRES4eZObxDsIdj4oQev7ZrzMMldLXmlkGslI8/oqiGc0X2A5/XwNO0gNGBd9UPjVI6bs1H8FEDFFm5j+LETrW8mconI5s3Lvv2roGS+vrV4tprKv10lz+nkSBEo5imT3P3cG6PZfPrMeTQWamvuHOAFk2J01oS+qMRl7llN1Z2XtDBNKPiU0JADDVQvzPvBr052xR7lM/dbwvRNoNAqSjxl3d3/sSEb+wMqdZUKgYtKiObh2BuGgNo/DfCBHXJaXSSGFZthz3H5zdMFeGo7jI6SSr2x1d2pY1M5spESZwtIud/B0oCQCcDygitBJNbOQ3w3qYtvoCjCSITPwIDAQAB");
        zfbPayConfig.setDecryptKey("gd0ZVuRZxl4ugW9G9qbYwA==");
        zfbPayConfig.setNotiry_url("http://client6.uqbike.cn/zhifubaoPay/alipayNotify.do");

        AlipaySystemOauthTokenResponse response = aliConfigService.alipaySystemOauthToken(null, null, zfbPayConfig);

        System.out.println(response);

    }


}
